(function() {

    'use strict';

    angular
        .module('app')
        .factory('ConfigModel', ConfigModel);

    ConfigModel.$inject = ['API','$cookies'];

    function ConfigModel( API,$cookies) {

        var service = {};

        try{  
            service.config = $cookies.getObject( 'c' );
        } catch(e) {
            $cookies.remove( 'c' );
        } 
        
        service.fetch = function () {
            var _this = this;
            return API.config.getConfig().then(function(data){
                _this.config = data.config;
                var exdate = new Date();
                exdate.setDate(exdate.getDate() +7);
                $cookies.putObject( 'c', data.config , {'expires': exdate});

                return data.config;
            });
        };

        service.getConfig = function(){
            if (this.config) {
                return this.config;
            } else{
                try{
                    this.config = $cookies.getObject( 'c' );
                } catch(e) {
                    $cookies.remove( 'c' );
                }
                return this.config;
            }
        };

        return service;

    }

})();